package com.pioneer.controller.archive;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pioneer.common.annotation.Log;
import com.pioneer.common.core.controller.BaseController;
import com.pioneer.common.core.domain.AjaxResult;
import com.pioneer.common.enums.BusinessType;
import com.pioneer.common.exception.CustomException;
import com.pioneer.common.utils.DictUtils;
import com.pioneer.web.archive.domain.ArcSupplier;
import com.pioneer.web.archive.service.IArcSupplierService;
import com.pioneer.web.system.domain.SysDictData;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 供应商管理
 *
 * @author hlm
 */
@RestController
@RequestMapping("/archive/supplier")
public class ArcSupplierController extends BaseController {

    @Resource
    private IArcSupplierService supplierService;

    /**
     * 获取供应商管理列表
     *
     * @param supplier 查询条件
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('archive:supplier:list')")
    @GetMapping("/list")
    public AjaxResult list(ArcSupplier supplier) {
        boolean isPage = startPage();
        List<ArcSupplier> list = supplierService.list(Wrappers.query(supplier));
        return success(isPage, list);
    }

    /**
     * 根据供应商管理id获取详细信息
     *
     * @param supplierId 供应商管理id
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('archive:supplier:query')")
    @GetMapping(value = "/{supplierId}")
    public AjaxResult getInfo(@PathVariable Long supplierId) {
        return AjaxResult.success(supplierService.getById(supplierId));
    }

    /**
     * 新增供应商管理
     *
     * @param supplier 供应商管理
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('archive:supplier:add')")
    @Log(title = "供应商管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ArcSupplier supplier) {
        if (supplierService.checkCodeUnique(supplier)) {
            return AjaxResult.error("供应商编码【" + supplier.getSupplierCode() + "】已存在，请重新输入");
        }
        return toAjax(supplierService.save(supplier));
    }

    /**
     * 修改供应商管理
     *
     * @param supplier 供应商管理
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('archive:supplier:edit')")
    @Log(title = "供应商管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ArcSupplier supplier) {
        if (supplierService.checkCodeUnique(supplier)) {
            return AjaxResult.error("供应商编码【" + supplier.getSupplierCode() + "】已存在，请重新输入");
        }
        return toAjax(supplierService.updateById(supplier));
    }

    /**
     * 删除供应商管理
     *
     * @param supplierIds 供应商管理id数组
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('archive:supplier:remove')")
    @Log(title = "供应商管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{supplierIds}")
    public AjaxResult remove(@PathVariable Long[] supplierIds) {
        return toAjax(supplierService.removeByIds(Arrays.asList(supplierIds)));
    }

    /**
     * 导出
     *
     * @param supplier 查询条件
     */
    @PreAuthorize("@ss.hasPerm('archive:supplier:export')")
    @Log(title = "供应商管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ArcSupplier supplier) {
        List<ArcSupplier> list = supplierService.list(Wrappers.query(supplier));
        if (CollUtil.isNotEmpty(list)) {
            List<SysDictData> typeList = DictUtils.getDictCache("arc_supplier_type");
            if (CollUtil.isEmpty(typeList)) {
                throw new CustomException("供应商行业数据字典为空，请在[系统管理-字段管理]节点进行维护！");
            }
            List<SysDictData> tradeList = DictUtils.getDictCache("arc_supplier_trade");
            if (CollUtil.isEmpty(tradeList)) {
                throw new CustomException("所属行业数据字典为空，请在[系统管理-字段管理]节点进行维护！");
            }
            List<SysDictData> creditList = DictUtils.getDictCache("arc_supplier_credit");
            if (CollUtil.isEmpty(creditList)) {
                throw new CustomException("信用等级数据字典为空，请在[系统管理-字段管理]节点进行维护！");
            }
            for (ArcSupplier arcSupplier : list) {
                typeList.stream().filter(type -> type.getDictValue().equals(arcSupplier.getType())).findFirst().ifPresent(type -> arcSupplier.setType(type.getDictLabel()));
                tradeList.stream().filter(trade -> trade.getDictValue().equals(arcSupplier.getTrade())).findFirst().ifPresent(trade -> arcSupplier.setTrade(trade.getDictLabel()));
                creditList.stream().filter(credit -> credit.getDictValue().equals(arcSupplier.getCredit())).findFirst().ifPresent(credit -> arcSupplier.setCredit(credit.getDictLabel()));
            }
        }

        LinkedHashMap<String, String> headMap = new LinkedHashMap<>();
        headMap.put("supplierId", "供应商ID");
        headMap.put("supplierCode", "供应商编码");
        headMap.put("supplierName", "供应商名称");
        headMap.put("supplierShortname", "供应商简称");
        headMap.put("type", "供应商类型");
        headMap.put("trade", "所属行业");
        headMap.put("legalPerson", "法定代表人");
        headMap.put("taxpayerNo", "纳税人登记号");
        headMap.put("registerFund", "注册资金");
        headMap.put("saleAddress", "营业地址");
        headMap.put("linkman", "联系人");
        headMap.put("phone", "电话");
        headMap.put("mobilePhone", "手机");
        headMap.put("url", "网址");
        headMap.put("email", "电子邮箱");
        headMap.put("zipCode", "邮政编码");
        headMap.put("credit", "信用等级");
        export(list, headMap);
    }

    @PreAuthorize("@ss.hasPerm('archive:supplier:import')")
    @Log(title = "供应商管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importDate(MultipartFile file) throws Exception {
        List<Map<String, Object>> list = ExcelUtil.getReader(file.getInputStream()).readAll();
        if (CollUtil.isEmpty(list)) {
            return AjaxResult.error("导入文件的数据为空，请检查！");
        }
        List<ArcSupplier> supplierList = new ArrayList<>();
        for (Map<String, Object> map : list) {
            JSONObject json = JSONUtil.parseObj(map);
            ArcSupplier supplier = new ArcSupplier();
            supplier.setSupplierCode(json.getStr("供应商编码"));
            supplier.setSupplierName(json.getStr("供应商名称"));
            supplier.setSupplierShortname(json.getStr("供应商简称"));
            supplier.setType(json.getStr("供应商类型"));
            supplier.setTrade(json.getStr("所属行业"));
            supplier.setLegalPerson(json.getStr("法定代表人"));
            supplier.setTaxpayerNo(json.getStr("纳税人登记号"));
            supplier.setRegisterFund(json.getStr("注册资金"));
            supplier.setSaleAddress(json.getStr("营业地址"));
            supplier.setLinkman(json.getStr("联系人"));
            supplier.setPhone(json.getStr("电话"));
            supplier.setMobilePhone(json.getStr("手机"));
            supplier.setUrl(json.getStr("网址"));
            supplier.setEmail(json.getStr("电子邮箱"));
            supplier.setZipCode(json.getStr("邮政编码"));
            supplier.setCredit(json.getStr("信用等级"));
            supplierList.add(supplier);
        }

        String msg = supplierService.importSupplier(supplierList);
        return AjaxResult.success(msg);
    }
}
